<template>
  <div>
    <div class="search_box">
      <el-form
        :inline="true"
        ref="ruleFormRef"
        :model="formData"
        :label-width="80"
      >
        <el-form-item label="推广时间">
          <selectDate ref="dateRef" type="daterange" @returnTime="returnTime" />
        </el-form-item>
        <el-form-item label="分销商">
          <el-select
            v-model="formData.tenantId"
            filterable
            placeholder="请选择分销商"
            clearable
          >
            <el-option
              v-for="item in distriOption"
              :key="item?.id"
              :label="item.label"
              :value="item?.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="剧目列表">
          <selectMultiple
            ref="multSelectRef"
            @selectChange="selectChange"
            :options="operaOptions"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="getList(1)"
            v-auth="'api:operate:chart:promotion'"
          >
            查 询
          </el-button>
          <el-button @click="resetList" v-auth="'api:operate:chart:promotion'">
            重 置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="table_box_wrapper">
      <el-button
        type="primary"
        class="export_box"
        @click="getList(9)"
        :loading="loadingExport"
      >
        数据导出
      </el-button>
      <custom-table
        :loading="loading"
        :columns="columns"
        :tableData="tableData"
        :pageObj="pageObj"
        @sizechange="sizechange"
        @currentChange="currentChange"
        :isCustomHead="true"
        class="table_box"
      >
        <template #date="{ scope }">
          <span v-if="scope.row?.date">
            {{ moment(scope.row?.date + "Z").format("YYYY-MM-DD") }}
          </span>
        </template>
      </custom-table>
    </div>
  </div>
</template>

<script setup lang="ts">
import customTable from "@/components/CustomTable/index.vue";
import { getPromotionList } from "@/api/operateCenter/chart/index";
// import { promotionSearchList } from "@/api/promotionLink/index";
import { operasSearch } from "@/api/operateCenter/episode/index";
import selectDate from "@/components/SeleteDate/index.vue";
import { searchTenant } from "@/api/operateCenter/distributor/index";
import moment from "moment";
import { exportTable } from "@/utils/tools";

const dateRef = ref();
let startT: number = new Date().getTime() - 3600000 * 24 * 6;
const loading = ref<boolean>(false);
const form = {
  tenantId: "", // 分销商Id
  pageNo: 1,
  pageSize: 10,
  start: moment(startT).startOf("day").format("YYYY-MM-DDTHH:mm:ss"),
  end: moment().startOf("day").format("YYYY-MM-DDTHH:mm:ss"),
  linkIds: [], // 推广链接id数组
  operaIds: [], // 剧目id
};
const formData = ref(Object.assign({}, form));
const valueTime = ref<any>("");
const tableData = ref<Array<any>>([]);
const promotionOptions = ref<Array<any>>([]);
const distriOption = ref<Array<any>>([]);
const operaOptions = ref<Array<any>>([]);
const multSelectRef = ref();
const loadingExport = ref(false);

interface modelPage {
  pageNo: number;
  pageSize: number;
  total: number;
}
const pageObj = reactive<modelPage>({
  pageNo: 1,
  pageSize: 10,
  total: 0,
});

const columns = reactive([
  {
    label: "日期",
    prop: "date",
    slotName: "date",
    minWidth: 100,
    fixed: "left",
  },
  { label: "推广链接名称", prop: "linkName", minWidth: 140, fixed: "left" },
  { label: "小程序名称", prop: "miniAppName", minWidth: 120 },
  { label: "linkId", prop: "linkId", minWidth: 120 },
  { label: "新增人数", prop: "newUsers", minWidth: 80 },
  {
    label: "新增充值金额(元)",
    prop: "newUsersRechargeAmount",
    minWidth: 135,
    formatter: (row: any) => {
      return `¥${row?.newUsersRechargeAmount}`;
    },
  },
  { label: "新增充值次数", prop: "newUsersRechargeTimes", minWidth: 110 },
  { label: "新增充值人数", prop: "rechargeNewUsers", minWidth: 110 },
  {
    label: "充值率",
    prop: "rechargeRate",
    minWidth: 80,
    formatter: (row: any) => {
      return `${row?.rechargeRate}%`;
    },
  },
  {
    label: "复购率",
    prop: "repurchaseRate",
    minWidth: 80,
    formatter: (row: any) => {
      return `${row?.repurchaseRate}%`;
    },
  },
  {
    label: "首充均价(元)",
    prop: "firstRechargeAverageAmount",
    minWidth: 105,
    formatter: (row: any) => {
      return `¥${row?.firstRechargeAverageAmount}`;
    },
  },
  { label: "二充均价", prop: "secondRechargeAverageAmount", minWidth: 80 },
  { label: "首日arppu", prop: "firstDayARPPU", minWidth: 95 },
  {
    label: "总充值金额(元)",
    prop: "rechargeAmountTotal",
    minWidth: 120,
    formatter: (row: any) => {
      return `¥${row?.rechargeAmountTotal}`;
    },
  },
  { label: "总充值次数", prop: "rechargeTimesTotal", minWidth: 95 },
  { label: "总充值人数", prop: "rechargeUsersTotal", minWidth: 95 },
]);

// 重置
const resetList = () => {
  formData.value = Object.assign(formData.value, form);
  multSelectRef.value.multipleData = []; // 重置组件多选
  dateRef.value.dateValue = [form.start, form.end];
  getList(1);
};

const getList = (val = 0) => {
  // if (!val) {
  //   formData.value.pageNo = pageObj.pageNo;
  //   formData.value.pageSize = pageObj.pageSize;
  // } else {
  //   formData.value.pageNo = pageObj.pageNo = val === 1 ? val : 1;
  //   formData.value.pageSize = pageObj.pageSize =
  //     val === 1 ? 10 : pageObj.pageSize;
  // }
  formData.value.pageNo = val && val === 9 ? 1 : pageObj.pageNo;
  formData.value.pageSize = val && val === 9 ? 100000 : pageObj.pageSize;

  // 数据导出不刷新列表
  if (val !== 9) {
    loading.value = true;
  } else {
    loadingExport.value = true;
  }
  getPromotionList(formData.value)
    .then((res: Record<string, any>) => {
      // 数据导出 中断后续数据渲染
      if (val === 9) {
        exportTable(res?.data, columns, "数据推广");
        loadingExport.value = false;
        return;
      }

      tableData.value = res.data;
      pageObj.total = Number(res?.total);
      loading.value = true;
    })
    .finally(() => {
      loading.value = false;
    });
};

const currentChange = (val: number) => {
  pageObj.pageNo = val;
  getList();
};

const sizechange = (val: number) => {
  pageObj.pageSize = val;
  getList(2);
};

// // 获取推广链接
// const getPromotionSearch = () => {
//   promotionSearchList({ pageNo: 1, pageSize: 1000 }).then(
//     (res: Record<string, any>) => {
//       promotionOptions.value = res.data.map((item: Record<string, any>) => {
//         return {
//           label: `id：${item.id} - ${item.linkName}`,
//           value: item?.id,
//         };
//       });
//     }
//   );
// };

// 获取分销商
const getTenantList = () => {
  searchTenant({ pageNo: 1, pageSize: 999 }).then(
    (res: Record<string, any>) => {
      distriOption.value = res?.data.map((item: Record<string, any>) => {
        return {
          label: item?.name,
          value: item?.id.toString(),
        };
      });
    }
  );
};

// 多选剧目
const selectChange = (val: any) => {
  formData.value.operaIds = val;
};

// 获取剧目
const getMovieList = () => {
  operasSearch({ pageNo: 1, pageSize: 1000 }).then(
    (res: Record<string, any>) => {
      operaOptions.value = res.data.map((item: Record<string, any>) => {
        return {
          label: `${item.id} - ${item.name}`,
          value: item?.id,
        };
      });
    }
  );
};

// 返回时间
const returnTime = (val: any) => {
  valueTime.value = val;
  formData.value.start = valueTime.value[0];
  formData.value.end = valueTime.value[1];
};

onMounted(() => {
  getList();
  // getPromotionSearch();
  getTenantList();
  getMovieList();
});
</script>

<style lang="scss" scoped>
.table_box_wrapper {
  margin-top: 15px;
  background-color: #fff;

  .export_box {
    margin: 10px 0 0 10px;
  }
}

.table_box {
  padding: 10px;
  border-radius: 4px;

  .movie_box {
    display: flex;
    align-items: center;

    img {
      width: 72px;
      height: 108px;
      margin-right: 8px;
    }

    span {
      flex: 1;
    }
  }
}
</style>
